import { _decorator, Component, game, Node } from 'cc';
import { BossInfo } from '../commonComp/InterfaceCom';
import { C2SEvent, GameEvent, WssEvent } from '../EventName';
import { GlobalVar } from '../GlobalVar';
import { InviteFriends } from '../Activity/InviteFriends';
import { Config } from '../Config';
const { ccclass, property } = _decorator;

@ccclass('WssComAD')
export class WssComAD {

  socket: WebSocket = null;



  start() {

  }




  initWs() {
    //const token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOiJhcGlfdXNlcjoxMDAwMTEiLCJyblN0ciI6IlBNU2N1R2J5QzJVWGxyRjM2RjZpODVSMVhkWDRVdlR0IiwiYXBpVXNlcklkIjoxMDAwMTF9.GjZ8QjoeuVi6QBLQ-Q5Z4TQyAhyph-ga_HzK-inbYZU";
    const encodedBaseInfo = btoa(`{"token":${GlobalVar.token}}`);
    // Generate random strings
    const prefix = this.generateRandomString(5); // Random string of 5 letters
    const suffix = this.generateRandomString(5); // Random string of 5 letters
    // Combine encoded data with random strings
    const finalData = prefix + encodedBaseInfo + suffix;
    // this.socket = new WebSocket(`wss://lastoasis.org/ws/boss?baseInfo=${finalData}`); //直接写路径
    //this.socket = new WebSocket(`ws://43.154.148.23/ws/boss?baseInfo=${finalData}`); //直接写路径
    this.socket = new WebSocket(Config.wssAD + `/adventure?baseInfo=${finalData}`); //直接写路径
    this.socket.binaryType = 'arraybuffer';
    this.socket.onclose = () => {
      console.log("WSSAD关闭")
      //game.emit(GameEvent.SHOW_TOAST, "The network connection has been disconnected")
      GlobalVar.isWssReady = false;
      //game.emit(GameEvent.SHOW_TOAST, "Connecting to server")
      //window.location.reload();
    };
    this.socket.onerror = ((ev) => {
      console.log("错误")
      console.log(ev)
      GlobalVar.isWssReady = false;
    })
    this.socket.onmessage = ((event) => {
      if (typeof event.data === 'string') {
        console.log('WSSAD Received message:', event.data);
      } else if (event.data instanceof ArrayBuffer) {
        const decoder = new TextDecoder();
        const str = decoder.decode(new Uint8Array(event.data));

        console.log('WSSAD 转JSON:', str);
        /**
         * cmd=1  boss数据
         * cmd=3  随机空投
         * cmd=4  boss掉落
         */
        // console.log('Received binary message:', str);

        let obj = JSON.parse(str);
        if (obj.cmd != 1) {
          console.log(obj, "wssAD onMessage-------------------")
        }
        switch (obj.cmd) {
          case 1:
            game.emit(WssEvent.ON_BOSSINFO_UPDATE, obj);
            break;
          case 2:


            break;
          case 3:

            game.emit(WssEvent.ON_AIRDROP_APPEAR, obj);
            break;
          case 4:

            game.emit(WssEvent.ON_BOSS_DROP, obj);
            break;
          case 8:

            game.emit(WssEvent.ON_ENTER_ADVENTURE_LAND_DATA, obj);
            break;
          case 9:

            game.emit(WssEvent.ON_ADVENTURE_LAND_DATA, obj);
            break;
          case 11:

            game.emit(WssEvent.ON_ADVENTURE_DIAMOND, obj);
            break;
          case 12:

            game.emit(WssEvent.ON_ADVENTURE_AUCTION, obj);
            break;
          case 13:

            game.emit(WssEvent.ON_ADVENTURE_REWARD, obj);
            break;
          case 14:

            game.emit(WssEvent.ON_ADVENTURE_AUCTION_REWARD, obj);
            break;
          case 15:

            game.emit(WssEvent.ON_ADVENTURE_BOOS, obj);
            break;
        }

      }
    })
    this.socket.onopen = (() => {
      console.log("WSSAD打开")
      game.emit(GameEvent.SHOW_TOAST, "WSSAD Server connection successful")
      //GlobalVar.isWssReady = true;
    })
  }


  generateRandomString(length) {
    const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    let result = '';
    for (let i = 0; i < length; i++) {
      result += charset.charAt(Math.floor(Math.random() * charset.length));
    }
    return result;
  }
  sendBinaryMessage(sendData: any) {
    //const msg = '{"cmd": 2}'
    const msg = JSON.stringify(sendData);
    // 使用 TextEncoder 将文本转换为二进制
    const encoder = new TextEncoder();
    const arrayBuffer = encoder.encode(msg); // 将文本编码为 Uint8Array
    this.socket.send(arrayBuffer);
    if (sendData.cmd != 2) {
      console.log(msg, "WSSAD向服务器发送消息");
    }
    //console.log('Binary message sent');
  }


  update(deltaTime: number) {

  }
}


